import jieba
from PyQt5.QtCore import Qt, QDate
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtGui import QTextCursor
import UI.NLP_UI as NLP_UI
import itemEditor
import logManager


class NLPUi(QMainWindow, NLP_UI.Ui_Dialog):
    def __init__(self, main_window: logManager.LogManagerUI):
        super(NLPUi, self).__init__()
        self.main_window = main_window
        self.setupUi(self)
        self.setWindowFlags(Qt.WindowMinimizeButtonHint)
        self.insert_html('我是你的NLP助手，请在下面的对话框中与我交流')
        self.dialog.moveCursor(QTextCursor.End)

    def on_insert(self):
        string = self.talkLineEdit.text()
        self.dialog.insertHtml('<p>%s<br></p>' % string)
        self.dialog.moveCursor(QTextCursor.End)
        self.talkLineEdit.clear()
        words = jieba.lcut(string)
        while ' ' in words:
            words.remove(' ')
        if '入库' in words:
            self.main_window.comboBox.setCurrentIndex(1)
            if '打印' in words:
                self.print_now(words, 1)
            else:
                self.edit_now(words, False)
        elif '出库' in words:
            self.main_window.comboBox.setCurrentIndex(2)
            # print('出库模式')
            if '打印' in words:
                self.print_now(words, 2)
            else:
                self.edit_now(words, True)
        elif '结余' in words:
            self.main_window.comboBox.setCurrentIndex(3)
            if '打印' in words:
                self.print_now(words, 3)
        elif '删除' in words:
            if self.main_window.comboBox.currentIndex() == 1 or self.main_window.comboBox.currentIndex() == 2:
                self.delete_now(words)
            else:
                self.insert_html('仅允许在“入库”或“出库”模式中删除记录')
        else:
            self.insert_html('关键词无效，试试说"入库","出库","删除"或"打印入库单"')

    def print_now(self, words: list, mode: int):
        self.main_window.comboBox.setCurrentIndex(mode)
        date_index = None
        for idx in range(len(words)):
            if words[idx] == '/':
                date_index = idx
                break
        if date_index is None:
            self.insert_html('若要进行打印，则必须指定日期')
            return
        try:
            year = int(words[date_index - 1])
            month = int(words[date_index + 1])
            day = int(words[date_index + 3])
        except ValueError:
            self.insert_html('日期格式不正确')
            return
        date = QDate()
        date.setDate(year, month, day)
        self.main_window.checkBox.setChecked(True)
        self.main_window.dateEdit.setDate(date)
        self.main_window.searchLineEdit.setText('')
        self.main_window.show_print()
        self.insert_html('操作成功完成')

    def edit_now(self, words: list, is_out: bool):
        idx: int = -114514
        item_editor = itemEditor.ItemEditorUI(is_out=is_out)
        for idx in range(len(item_editor.typeData)):
            if item_editor.typeData[idx] in words:
                item_editor.comboBox.setCurrentIndex(idx)
                break
        if item_editor.unitLineEdit.text() == '':
            self.insert_html('你可能还未设置过单位或者货物类型，请检查')
            return
        flag = False
        for item in words:
            if item_editor.unitLineEdit.text() in item:
                flag = True
        if ('元' in words or is_out) and flag:
            pass
        else:
            flag = False
        if flag:
            try:
                idx = words.index(item_editor.unitLineEdit.text())
            except ValueError:
                self.insert_html('单位错误，ps：如果使用英文单位，请手动在数字后加空格')
            if not is_out:
                idx2 = words.index('元')
                try:
                    _ = float(words[idx2 - 1])
                except ValueError:
                    self.insert_html('关键词不足 ps:使用阿拉伯数字')
                    return
                except IndexError:
                    self.insert_html('关键词不足 ps:使用阿拉伯数字')
                    return
                item_editor.unitPriceLineEdit.setText(words[idx2 - 1])

            try:
                _ = float(words[idx-1])
            except IndexError:
                self.insert_html('关键词不足 ps:使用阿拉伯数字')
                return
            except ValueError:
                self.insert_html('关键词不足 ps:使用阿拉伯数字')
                return
            item_editor.numberLineEdit.setText(words[idx-1])
            item_editor.add()
            self.main_window.reload()
            self.insert_html('操作成功完成')
        else:
            self.insert_html('关键词不足 ps:别忘了带单位哦~')

    def delete_now(self, words: list):
        if '号' in words:
            try:
                idx = int(words[words.index('号')-1])-1
            except ValueError or IndexError:
                self.insert_html('关键词不足 ps:使用阿拉伯数字')
                return
            model_index = self.main_window.tableViewModel.index(idx, 0)
            self.main_window.tableView.setCurrentIndex(model_index)
            self.main_window.remove()
            self.insert_html('操作成功完成')
        else:
            self.insert_html('关键词不足 ps:别忘了加单位~')

    def insert_html(self, string: str):
        self.dialog.insertHtml('<p style="font-weight:bold;">%s<br></p>' % string)
        self.dialog.moveCursor(QTextCursor.End)
